package cn.wolfcode.thread;

/**
 * volatile
 * 可见性:对所有线程可见
 * 禁止指令重新排序优化
 */
public class TestJVMModel {
    public static void main(String[] args) {
        JVMModel jvmModel = new JVMModel();
        new Thread(jvmModel).start();

        for (int i = 0; i < 100; i++) {
            System.out.println(1);
            if (jvmModel.isFlag()) {
                System.out.println(2);
                System.out.println("------");
                break;
            }
        }
    }
}

class JVMModel implements Runnable {
//    private boolean flag = false;
    private volatile boolean flag = false;

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public void run() {
        System.out.println(3);
//        try {
//            Thread.sleep(200L);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        flag = true;
        System.out.println(4);
        System.out.println(Thread.currentThread().getName() + "flag" + flag);
    }
}
